//
// Created by Suzhen on 2017/1/5.
//

#ifndef ORIONV2_HTTPREQUEST_H
#define ORIONV2_HTTPREQUEST_H

#include "Orion.h"
#include <http_parser.h>

ORION_V2_NAMESPACE_BEGIN

        //not thread safe
        class HttpRequest : public EnhanceSupport::MRCSupport {
            // ================== HTTP PARSER CALLBACK BEGIN ==================
        private:

            static int OnMessageBegin(http_parser *);

            static int OnUrl(http_parser *, const char *at, size_t length);

            static int OnHeaderField(http_parser *, const char *at, size_t length);

            static int OnHeaderValue(http_parser *, const char *at, size_t length);

            static int OnHeaderComplete(http_parser *);

            static int OnBody(http_parser *, const char *at, size_t length);

            static int OnMessageComplete(http_parser *);
            // ================== HTTP PARSER CALLBACK END ==================
        public:

            HttpRequest();

            virtual ~HttpRequest();

            void executeParse(const char *, size_t len);

            void printDetails();

            const std::string &getUrl() const;

            const std::map<std::string, std::string> &getHeaders() const;

            std::string getBody() const;

            bool hasErr() const;

            bool hasDone() const;

        private:

            enum HttpRequestStatus {
                MSG_UNDEF,
                MSG_BREAK,
                MSG_BEGIN,
                MSG_URL,
                MSG_HEADER,
                MSG_BODY,
                MSG_END
            };
            //inner status machine
            std::string tempHeaderKey_{};
            HttpRequestStatus currentStatus_{MSG_UNDEF};
            //http parser objects
            http_parser_type parseType_;
            http_parser_settings settings_;
            http_parser parser_;
            //http fields
            std::string url_{};
            std::map<std::string, std::string> headers_{};
            std::ostringstream contentBodyStream_{""};

        };

ORION_V2_NAMESPACE_END


#endif //ORIONV2_HTTPREQUEST_H
